/**
 * 比例尺网格组件
 * 用于在编辑模式下显示场景尺寸参考
 */

import * as THREE from 'three';

export class ScaleGrid {
    constructor() {
        this.gridGroup = new THREE.Group();
        this.gridGroup.name = 'ScaleGrid';
        
        // 配置
        this.gridSize = 50; // 网格总大小
        this.gridDivisions = 50; // 网格分割数（每格1米）
        this.unitSize = 1; // 每格代表1米
        this.visible = true;
        
        // 屏幕比例尺
        this.screenScaleElement = null;
        this.camera = null;
        
        this.createGrid();
        this.createScaleLabels();
        this.createAxisLabels();
        this.initScreenScale();
    }
    
    /**
     * 初始化屏幕比例尺
     */
    initScreenScale() {
        this.screenScaleElement = document.getElementById('screen-scale-indicator');
        if (this.screenScaleElement) {
            console.log('✅ 屏幕比例尺已初始化');
        }
    }
    
    /**
     * 设置相机引用（用于计算比例尺）
     */
    setCamera(camera) {
        this.camera = camera;
        if (camera) {
            console.log('✅ 比例尺已关联相机');
            this.updateScreenScale();
        }
    }
    
    /**
     * 更新屏幕比例尺显示
     */
    updateScreenScale() {
        if (!this.screenScaleElement || !this.camera) return;
        
        // 计算相机到原点的距离
        const cameraPosition = this.camera.position;
        const distance = Math.sqrt(
            cameraPosition.x * cameraPosition.x + 
            cameraPosition.y * cameraPosition.y + 
            cameraPosition.z * cameraPosition.z
        );
        
        // 根据相机距离和FOV计算屏幕比例尺
        // 假设屏幕比例尺线条宽度为100px
        const fov = this.camera.fov || 75;
        const aspect = window.innerWidth / window.innerHeight;
        
        // 计算视野宽度（以米为单位）
        const vFOV = fov * Math.PI / 180;
        const viewHeight = 2 * Math.tan(vFOV / 2) * distance;
        const viewWidth = viewHeight * aspect;
        
        // 100px在屏幕上代表的实际距离（米）
        const pixelToMeter = viewWidth / window.innerWidth;
        const scaleDistance = pixelToMeter * 100;
        
        // 智能选择合适的显示单位
        let displayValue, displayUnit;
        if (scaleDistance < 1) {
            displayValue = Math.round(scaleDistance * 100);
            displayUnit = 'cm';
        } else if (scaleDistance < 10) {
            displayValue = (scaleDistance).toFixed(1);
            displayUnit = 'm';
        } else if (scaleDistance < 1000) {
            displayValue = Math.round(scaleDistance);
            displayUnit = 'm';
        } else {
            displayValue = (scaleDistance / 1000).toFixed(2);
            displayUnit = 'km';
        }
        
        // 更新显示
        const label = this.screenScaleElement.querySelector('.scale-label');
        if (label) {
            label.textContent = `${displayValue}${displayUnit}`;
        }
    }
    
    /**
     * 创建网格
     */
    createGrid() {
        // 主网格（每5米一条粗线）
        const mainGridHelper = new THREE.GridHelper(
            this.gridSize, 
            this.gridSize / 5, 
            0x888888, 
            0x444444
        );
        mainGridHelper.name = 'MainGrid';
        mainGridHelper.material.opacity = 0.3;
        mainGridHelper.material.transparent = true;
        this.gridGroup.add(mainGridHelper);
        
        // 细网格（每1米一条细线）
        const fineGridHelper = new THREE.GridHelper(
            this.gridSize, 
            this.gridDivisions, 
            0x666666, 
            0x333333
        );
        fineGridHelper.name = 'FineGrid';
        fineGridHelper.material.opacity = 0.15;
        fineGridHelper.material.transparent = true;
        this.gridGroup.add(fineGridHelper);
    }
    
    /**
     * 创建刻度标签（每5米显示一个数字，更大更清晰）
     */
    createScaleLabels() {
        const labelsGroup = new THREE.Group();
        labelsGroup.name = 'ScaleLabels';
        
        const interval = 5; // 每5米显示一个标签
        const halfSize = this.gridSize / 2;
        
        // 创建文字材质（增强版 - 更大、更清晰、带背景）
        const createTextSprite = (text, color = '#FFFFFF', isMainLabel = true) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = 256;  // 增大画布尺寸
            canvas.height = 128;
            
            // 清空背景
            context.fillStyle = 'rgba(0, 0, 0, 0)';
            context.fillRect(0, 0, canvas.width, canvas.height);
            
            if (isMainLabel) {
                // 绘制半透明背景矩形，提高可读性
                context.fillStyle = 'rgba(0, 0, 0, 0.6)';
                context.roundRect = function(x, y, w, h, r) {
                    this.beginPath();
                    this.moveTo(x + r, y);
                    this.lineTo(x + w - r, y);
                    this.arcTo(x + w, y, x + w, y + r, r);
                    this.lineTo(x + w, y + h - r);
                    this.arcTo(x + w, y + h, x + w - r, y + h, r);
                    this.lineTo(x + r, y + h);
                    this.arcTo(x, y + h, x, y + h - r, r);
                    this.lineTo(x, y + r);
                    this.arcTo(x, y, x + r, y, r);
                    this.closePath();
                    return this;
                };
                context.roundRect(20, 20, 216, 88, 10);
                context.fill();
                
                // 绘制边框
                context.strokeStyle = color;
                context.lineWidth = 3;
                context.stroke();
            }
            
            // 绘制文字
            context.font = 'Bold 56px Arial';  // 增大字体
            context.fillStyle = color;
            context.textAlign = 'center';
            context.textBaseline = 'middle';
            
            // 添加文字阴影效果
            context.shadowColor = 'rgba(0, 0, 0, 0.8)';
            context.shadowBlur = 4;
            context.shadowOffsetX = 2;
            context.shadowOffsetY = 2;
            
            context.fillText(text, canvas.width / 2, canvas.height / 2);
            
            const texture = new THREE.CanvasTexture(canvas);
            texture.needsUpdate = true;
            
            const spriteMaterial = new THREE.SpriteMaterial({
                map: texture,
                transparent: true,
                opacity: 0.95,  // 提高透明度
                depthTest: false,
                depthWrite: false
            });
            
            const sprite = new THREE.Sprite(spriteMaterial);
            sprite.scale.set(4, 2, 1);  // 增大标签尺寸
            
            return sprite;
        };
        
        // X轴标签（红色）
        for (let i = -halfSize; i <= halfSize; i += interval) {
            if (i === 0) continue; // 原点不显示
            const sprite = createTextSprite(`${Math.abs(i)}m`, '#FF6B6B');
            sprite.position.set(i, 0.2, -halfSize - 3);  // 调整位置
            labelsGroup.add(sprite);
        }
        
        // Z轴标签（蓝色）
        for (let i = -halfSize; i <= halfSize; i += interval) {
            if (i === 0) continue; // 原点不显示
            const sprite = createTextSprite(`${Math.abs(i)}m`, '#4DABF7');
            sprite.position.set(-halfSize - 3, 0.2, i);  // 调整位置
            labelsGroup.add(sprite);
        }
        
        // 原点标签（白色高亮）
        const originSprite = createTextSprite('0m', '#FFFFFF');
        originSprite.position.set(-2, 0.2, -2);
        labelsGroup.add(originSprite);
        
        this.gridGroup.add(labelsGroup);
    }
    
    /**
     * 创建坐标轴标签
     */
    createAxisLabels() {
        const axesGroup = new THREE.Group();
        axesGroup.name = 'AxisLabels';
        
        const createAxisSprite = (text, color) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = 128;
            canvas.height = 128;
            
            context.fillStyle = 'rgba(0, 0, 0, 0)';
            context.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制圆形背景
            context.beginPath();
            context.arc(64, 64, 50, 0, Math.PI * 2);
            context.fillStyle = color;
            context.fill();
            
            // 绘制文字
            context.font = 'Bold 56px Arial';
            context.fillStyle = '#FFFFFF';
            context.textAlign = 'center';
            context.textBaseline = 'middle';
            context.fillText(text, 64, 64);
            
            const texture = new THREE.CanvasTexture(canvas);
            texture.needsUpdate = true;
            
            const spriteMaterial = new THREE.SpriteMaterial({
                map: texture,
                transparent: true,
                opacity: 0.9,
                depthTest: false,
                depthWrite: false
            });
            
            const sprite = new THREE.Sprite(spriteMaterial);
            sprite.scale.set(3, 3, 1);
            
            return sprite;
        };
        
        // X轴标签（红色 - 指向正X方向）
        const xLabel = createAxisSprite('X', '#FF0000');
        xLabel.position.set(this.gridSize / 2 + 3, 1, 0);
        axesGroup.add(xLabel);
        
        // Z轴标签（蓝色 - 指向正Z方向）
        const zLabel = createAxisSprite('Z', '#0000FF');
        zLabel.position.set(0, 1, this.gridSize / 2 + 3);
        axesGroup.add(zLabel);
        
        this.gridGroup.add(axesGroup);
    }
    
    /**
     * 添加到场景
     */
    addToScene(scene) {
        if (scene && !scene.getObjectByName('ScaleGrid')) {
            scene.add(this.gridGroup);
            console.log('✅ 比例尺已添加到场景');
        }
    }
    
    /**
     * 从场景移除
     */
    removeFromScene(scene) {
        if (scene) {
            const grid = scene.getObjectByName('ScaleGrid');
            if (grid) {
                scene.remove(grid);
                console.log('🗑️  比例尺已从场景移除');
            }
        }
    }
    
    /**
     * 显示比例尺
     */
    show() {
        this.gridGroup.visible = true;
        this.visible = true;
        console.log('👁️  比例尺已显示');
    }
    
    /**
     * 隐藏比例尺
     */
    hide() {
        this.gridGroup.visible = false;
        this.visible = false;
        console.log('🙈 比例尺已隐藏');
    }
    
    /**
     * 切换显示/隐藏
     */
    toggle() {
        if (this.visible) {
            this.hide();
        } else {
            this.show();
        }
    }
    
    /**
     * 销毁比例尺，释放资源
     */
    dispose() {
        this.gridGroup.traverse((child) => {
            if (child.material) {
                if (child.material.map) {
                    child.material.map.dispose();
                }
                child.material.dispose();
            }
            if (child.geometry) {
                child.geometry.dispose();
            }
        });
        
        this.gridGroup.clear();
        console.log('🗑️  比例尺资源已释放');
    }
    
    /**
     * 更新网格大小
     */
    updateGridSize(size) {
        this.gridSize = size;
        this.gridDivisions = size;
        
        // 清除旧网格
        this.gridGroup.clear();
        
        // 重新创建
        this.createGrid();
        this.createScaleLabels();
        this.createAxisLabels();
        
        console.log(`🔄 比例尺已更新，大小: ${size}m × ${size}m`);
    }
}

export default ScaleGrid;

